<template>
  <div class="search-result-container">
    <!-- 点击实现后退效果 -->
    <van-nav-bar
      title="搜索结果"
      left-arrow
      @click-left="$router.go(-1)"
      fixed
    />
    <div>
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArticleItem
          v-for="(item, index) in articleList"
          :key="index"
          :item="item"
          :show="false"
        ></ArticleItem>
      </van-list>
    </div>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem'
import { SearchResultAPI } from '@/api'
export default {
  data () {
    return {
      page: 1, // 默认显示第一页 - 搜索结果页面
      articleList: [], // 文章数据列表
      loading: false,
      finished: false
    }
  },
  name: 'SearchResult',
  components: {
    ArticleItem
  },
  async created () {
    const [, res] = await SearchResultAPI({
      q: this.$route.params.keywords,
      page: this.page
    })
    this.articleList = res.data.data.results
  },
  methods: {
    onLoad () {
      this.getResultList()
    },
    async getResultList () {
      const kw = this.$route.params.keywords
      const [, res] = await SearchResultAPI({
        q: kw,
        page: this.page
      })
      // 判断数据是否加载完毕
      if (res.data.data.results.length === 0) {
        this.finished = true
      } else {
        // 合并2个数组数据
        this.articleList = [...this.articleList, ...res.data.data.results]
        // 重置加载状态
        this.loading = false
        // 页码值 + 1
        this.page++
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-result-container {
  padding-top: 46px;
}
</style>
